package Twice.day11;

import java.util.LinkedList;
import java.util.Scanner;

/**
 * @Author: lya
 * @Description: 本类的作用描述:
 * @CreateDate: 2019/8/6
 * @Version: 1.0
 */
public class BracketDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入括号:>");

        String line = sc.nextLine();

        boolean flag = match(line);

        if(flag){
            System.out.println("匹配!");
        }else{
            System.out.println("不匹配!");
        }
    }
@SuppressWarnings("all")
    private static boolean match(String line) {
        //将字符串换成字符数组
        char[] arr = line.toCharArray();

        //创建一个LinkedList集合
        LinkedList<Character> list = new LinkedList<>();

        //将字符数组的第一个元素压入栈顶
        list.push(arr[0]);

        //从字符数组中的第二个元素开始遍历
        for (int i = 0; i < arr.length; i++) {
            Character c1 = null;
            Character c2 = arr[i];
            if(list.isEmpty()){//栈顶不存在元素
                //将当前元素压入栈
                list.push(c2);
                continue;
            }
            //存在栈顶
            c1 = list.getFirst();
            if(c1.equals('(') && c2.equals(')') || c1.equals('[') && c2.equals(']') || c1.equals('{') && c2.equals('}')) {
                //弹出栈顶内容
                list.pop();
            }else{
                list.push(c2);
            }
        }
        return list.isEmpty();//如果为空说明匹配成功
    }
}
